package com.lcx.plugin.handle;

import com.google.common.collect.Lists;
import com.lcx.plugin.dto.DbConfigDTO;
import com.lcx.plugin.tool.CacheDataUtils;
import com.lcx.plugin.tool.ComponentUtil;
import com.lcx.plugin.tool.ListSplitUtil;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * jdbc处理器，获取连接，执行sql
 *
 * @author daxiong
 * @date 2023/6/15 下午1:16
 */
@Slf4j
public class JdbcHandle {

    DbConfigDTO dbConfig;

    /**
     * 数据缓存工具类
     */
    private final CacheDataUtils cacheDataUtils = CacheDataUtils.getInstance();

    public JdbcHandle(DbConfigDTO dbConfig) {
        this.dbConfig = dbConfig;
        try {
            Class.forName(dbConfig.getDriver());
        } catch (ClassNotFoundException e) {
            log.error("找不到Driver驱动类");
        }
    }

    public void executeSql(String sql) {
        try (
                // Connection连接对象
                Connection connection = DriverManager.getConnection(
                        dbConfig.getUrl(), dbConfig.getUser(), dbConfig.getPass());
                // 创建一个执行sql的statement对象
                Statement statement = connection.createStatement()
        ) {
            // 批量执行sql
            List<String> allList = Lists.newArrayList(sql.split(";"));
            // 如果数据太多，则分批执行
            List<List<String>> groupList = ListSplitUtil.groupList(allList);
            for (List<String> list : groupList) {
                statement.clearBatch();
                for (String s : list) {
                    if (s.length() > 2) {
                        // list的最后一个元素是"\n\n"，长度为2
                        statement.addBatch(s);
                    }
                }
                statement.executeBatch();
            }

            ComponentUtil.showNotification(cacheDataUtils.getProject(), "表创建成功", true);
        } catch (SQLException exception) {
            log.error(exception.getMessage());
            ComponentUtil.showNotification(cacheDataUtils.getProject(), exception.getMessage(), false);
        }
    }

    /**
     * 测试连接
     *
     * @return boolean
     * @author daxiong
     * @date 2023/6/16 下午3:20
     */
    public boolean testConnect() {
        try (
                // Connection连接对象
                Connection connection = DriverManager.getConnection(
                        dbConfig.getUrl(), dbConfig.getUser(), dbConfig.getPass());
                // 创建一个执行sql的statement对象
                Statement statement = connection.createStatement()
        ) {
            // 执行sql
            ResultSet set = statement.executeQuery("select 1");
            // 看结果
            while (set.next()) {
                System.out.println(set.getString(1));
            }
            return true;
        } catch (SQLException exception) {
            log.error(exception.getMessage());
            return false;
        }
    }

}
